import sys
from pathlib import Path
from datetime import datetime

from git import Repo

from config import committers


def switch_jsvm(rnoh_dir: Path):
    res = ""

    # set_cmake_path = rnoh_dir / "tester/harmony/entry/src/main/cpp/CMakeLists.txt"
    # content = set_cmake_path.read_text()
    # content = content.replace("set(LOG_VERBOSITY_LEVEL 1)", "set(LOG_VERBOSITY_LEVEL 1)\nset(USE_HERMES 0)")
    # set_cmake_path.write_text(content)
    # res += content

    ON = 'option(USE_HERMES "Enabled or Disable the Hermes JS Engine" ON)'
    OFF = 'option(USE_HERMES "Enabled or Disable the Hermes JS Engine" OFF)'
    option_cmake_path = rnoh_dir / "tester/harmony/react_native_openharmony/src/main/cpp/CMakeLists.txt"
    content = option_cmake_path.read_text()
    assert ON in content or OFF in content, "no hermes option found"
    content = content.replace(ON, OFF)
    option_cmake_path.write_text(content)
    res += content
    return res


def get_commit_info_from_disk(project_fdr: Path):
    repo = Repo(project_fdr)
    commit = repo.head.commit
    return get_commit_info(repo, commit)


def get_commit_info(repo: Repo, commit):
    return {
        "hash": commit.hexsha,
        "author": commit.author.name,
        "date": datetime.fromtimestamp(commit.committed_date).strftime("%Y%m%d_%H%M%S"),
        "message": commit.message.strip(),
        "is_merge": commit.committer.name in committers,
        "committer": commit.committer.name,
        "parents": [parent.hexsha for parent in commit.parents],  # Get parent commit hashes
        "tags": [tag.name for tag in repo.tags if tag.commit == commit],  # Get tags pointing to this commit
    }


def change_vendor(rnoh_dir: Path, build_type: str) -> str:
    app_config_path = rnoh_dir / "tester/harmony/AppScope/app.json5"
    info = get_commit_info_from_disk(rnoh_dir)
    compiler = "bisheng" if "BiSheng" in (rnoh_dir / "tester/harmony/build-profile.json5").read_text() else "clang"
    vendor = f'{info["date"]}@{info["hash"]}{"@" + "_".join(info["tags"]) if len(info["tags"]) else ""}@{compiler}@{build_type}'

    content = app_config_path.read_text()
    lines = content.splitlines()

    updated_lines = []
    for line in lines:
        if '"vendor"' in line:
            updated_lines.append(f'    "vendor": "{vendor}",')
            print(line)
        else:
            updated_lines.append(line)
    updated = "\n".join(updated_lines) + "\n"
    # updated = updated.replace('"bundleName": "com.rnoh.tester",', '"bundleName": "com.acts.ace.napitest",')
    app_config_path.write_text(updated)
    return str(app_config_path) + "\n" + updated


def add_sign_config(config_path: Path):
    assert config_path.exists(), str(config_path) + " does not exist"
    content = config_path.read_text()
    content = content.replace(
        "    signingConfigs: [],",
        """
    signingConfigs: [
      {
        name: 'default',
        type: 'HarmonyOS',
        material: {
          certpath: '/home/user/Desktop/keep/keys/default_harmony_b422_-axahpxjW18hDhIheU_WyYq3M-DKVsmhbAb4dY=.cer',
          storePassword: '0000001A68054788A5D2152C0978E315CCF638E9BC382D7504448F614A380B5A1E3A1566F6539C9632F2',
          keyAlias: 'debugKey',
          keyPassword: '0000001A6AF341186AB20B72B99263CEAA653D2DA8E1270A3E2C6A668DFAC50426C44C515007D47809C1',
          profile: '/home/user/Desktop/keep/keys/default_harmony_b422_-axahpxjW18hDhIheU_WyYq3M-DKVsmhbAb4dY=.p7b',
          signAlg: 'SHA256withECDSA',
          storeFile: '/home/user/Desktop/keep/keys/default_harmony_b422_-axahpxjW18hDhIheU_WyYq3M-DKVsmhbAb4dY=.p12',
        },
      },
    ],
    """,
    )
    config_path.write_text(content)


def more_cxx_option(rnoh_dir: Path, options: str):
    option_cmake_path = rnoh_dir / "tester/harmony/entry/src/main/cpp/CMakeLists.txt"
    content = option_cmake_path.read_text()
    assert "CMAKE_CXX_FLAGS" in content, "no CMAKE_CXX_FLAGS found"
    lines = content.splitlines()
    res = []
    for line in lines:
        if "CMAKE_CXX_FLAGS" in line:
            res.append(line.replace('")', f' {options}")'))
        else:
            res.append(line)
    option_cmake_path.write_text("\n".join(res))
    return str(option_cmake_path) + "\n" + "\n".join(res)


def no_bisheng(rnoh_dir: Path):
    build_profile_path = rnoh_dir / "tester/harmony/build-profile.json5"
    content = build_profile_path.read_text()
    if not "BiSheng" in content:
        return

    res = []
    for line in content.splitlines():
        print(line)
        if "nativeCompiler" in line and "BiSheng" in line:
            print(line)
        else:
            res.append(line)
    build_profile_path.write_text("\n".join(res))


if __name__ == "__main__":
    if sys.argv[1] == "switch_jsvm":
        switch_jsvm(Path(sys.argv[2]))
    if sys.argv[1] == "change_vendor":
        change_vendor(Path(sys.argv[2]), sys.argv[3])
    if sys.argv[1] == "add_sign_config":
        add_sign_config(Path(sys.argv[2]))
    if sys.argv[1] == "more_cxx_option":
        more_cxx_option(Path(sys.argv[2]), sys.argv[3])
    if sys.argv[1] == "no_bisheng":
        no_bisheng(Path(sys.argv[2]))
